<template>
  <div>
    <el-button @click="print" type="primary" :loading="loading">开始打印</el-button>
    起始位置：<el-input v-model.number="pdfNum" placeholder="起始位置,从0开始" style="width: 200px;"></el-input>
    错误{{errorArr.length}}个
    <div id="playerDetailPrint" style="padding: 0 50px 50px 50px;overflow: visible;width: 1000px;">
      <empDetailPrint :detailData="detailData" ref="playerDetailPrint" @cultureResultReturned="cultureResultReturned"></empDetailPrint>
    </div>
  </div>
</template>

<script>
  import html2Canvas from 'html2canvas'
  import JsPDF from 'jspdf'
  // import VueHtml2pdf from 'vue-html2pdf'
  import { getDetail,empInit } from '@/api/person.js'
  import empDetailPrint from '@/components/print/empDetailPrint.vue'
  export default {
    components: {empDetailPrint},
    data() {
      return {
        printTopData: ['emp_basic','emp_detail','family','emp_languageLevel','emp_workExp','education','emp_paper','emp_referee','emp_rewordPunishment','emp_furtherEdu'],
        detailData: {},
        defaultPlayerData: [],
        fileName: '',
        download: false,
        pdfSave: 1,
        pdfNum: 0,
        errorArr: [],
        loading: false,
      }
    },
    computed: {
      pdfOptions() {
        return {
          margin: [0, 5, 0, 5],
          pagebreak: { mode: 'avoid-all'}
        }
      },
    },
    created() {
      this.pdfNum = parseInt(window.localStorage.getItem('empPdfNum'))
      if(!this.pdfNum) this.pdfNum = 0
      this.getPlayer()
    },
    watch: {
      fileName(val,old) {
        let dom = document.getElementById('playerDetailPrint')
        this.getPdfFromHtml(dom,old+'个人档案')
      },
      // pdfSave(val){
      //   this.pdfNum += 1

      // }
    },
    methods: {
      cultureResultReturned(name) {
        this.fileName = name
      },
      print() {
        window.localStorage.setItem('empPdfNum',this.pdfNum)
        this.loading = true
        if(this.defaultPlayerData.length==0){
          this.$message.error('没有数据怎么打印？！！！')
          return
        }
        if(this.pdfNum!=this.defaultPlayerData.length){
          this.playerDetailPrint(this.defaultPlayerData[this.pdfNum].pid)
        }
      },
      playerDetailPrint(pId) {
        if(this.printTopData.length != 0){
          let data = {
            pId: pId,
            data: {personInfoPrintSpec: this.printTopData.join(',')}
          }
          getDetail(data).then(res=>{
            if(res.code === 200) {
              this.detailData = res.data
            }else{
              this.errorArr.push(pId)
              this.pdfNum += 1
              this.print()
            }
          })
        }else{
          this.$message.error('至少选择一项打印！')
        }
      },
      getPlayer() {
        empInit().then(res=>{
          if(res.code === 200 && res.data.length!=0) {
            this.defaultPlayerData = res.data
            this.defaultPlayerData.push(this.defaultPlayerData[0])
          }else{
            this.defaultPlayerData = []
          }
        })
      },
      getPdfFromHtml(ele, pdfFileName) {
            html2Canvas(ele,{
              dpi: window.devicePixelRatio * 4,
              scale: 4,
              useCORS: true,//允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
              allowTaint: false,
              height: ele.offsetHeight,
              width: ele.offsetWidth,
              windowWidth: document.body.scrollWidth,
              windowHeight: document.body.scrollHeight,
            }).then(canvas=>{
              this.dialogVisible = true;
              const _this = this;
              //未生成pdf的html页面高度
              var leftHeight = canvas.height;
              var a4Width = 595.28
              var a4Height = 841.89
              //一页pdf显示html页面生成的canvas高度;
              var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height);

              //pdf页面偏移
              var position = 0;

              var pageData = canvas.toDataURL('image/jpeg', 1.0);

              var pdf = new JsPDF('x', 'pt', 'a4');
              var index = 1,
                canvas1 = document.createElement('canvas'),
                height;
              pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');

              // $('.head-content').append($(
              //   '<div class="pdfTip">' +
              //   '   <div>正在生成第<span class="pdfProgress">1</span>页，共<span class="pdfTotal"></span>页...' +
              //   '</div>'));
              function createImpl(canvas) {
                if (leftHeight > 0) {
                  index++;
                  var checkCount = 0;
                  if (leftHeight > a4HeightRef) {
                    var i = position + a4HeightRef;
                    for (i = position + a4HeightRef; i >= position; i--) {
                      var isWrite = true
                      for (var j = 0; j < canvas.width; j++) {
                        var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data

                        if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
                          isWrite = false
                          break
                        }
                      }
                      if (isWrite) {
                        checkCount++
                        if (checkCount >= 10) {
                          break
                        }
                      } else {
                        checkCount = 0
                      }
                    }
                    height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
                    if(height<=0){
                      height = a4HeightRef;
                    }
                  } else {
                    height = leftHeight;
                  }

                  canvas1.width = canvas.width;
                  canvas1.height = height;

                  // console.log(index, 'height:', height, 'pos', position);

                  var ctx = canvas1.getContext('2d');
                  ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height);

                  var pageHeight = Math.round(a4Width / canvas.width * height);
                  // pdf.setPageSize(null, pageHeight)
                  if(position != 0){
                    pdf.addPage();
                  }
                  pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 20, a4Width, a4Width / canvas1.width * height);

                  // var canvasBlank = document.createElement('canvas');
                  // var ctx2 = canvasBlank.getContext('2d');
                  // canvasBlank.width = 600;
                  // canvasBlank.height = 20;
                  // canvasBlank.style.border = '1px solid red';

                  // //绘制矩形ctx.rect(x,y,w,h);
                  // //前两个参数表示矩形左上角的点的x,y坐标，w,h表示矩形的宽高。
                  // ctx2.rect(100,50,100,100);
                  // ctx2.stroke();

                  // //描边矩形
                  // ctx2.strokeRect(100,200,200,100);

                  // //填充矩形,默认填充黑色
                  // ctx2.fillRect(100,350,300,200);

                  // pdf.addImage(canvasBlank.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 0, canvasBlank.width, canvasBlank.height);

                  leftHeight -= height;
                  position += height;
                  // $('.pdfProgress').text(index + 1);
                  // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
                  if (leftHeight > 0) {
                    //添加全屏水印
                    // const base64 = ''
                    // for(let i=0;i<6;i++){
                    //   for(let j=0;j<5;j++){
                    //     const  left = (j*120)+20;
                    //     pdf.addImage(base64,'JPEG', left, i*150, 20, 30);
                    //   }
                    // }
                    setTimeout(createImpl, 500, canvas);
                  } else {
                    // _this.iframeSrc = pdf.output('dataurlstring');
                    // debugger;
                    this.pdfSave = pdf.save(pdfFileName + '.pdf');
                  }
                }
              }

              //当内容未超过pdf一页显示的范围，无需分页
              if (leftHeight < a4HeightRef) {
                pdf.addImage(pageData, 'JPEG', 0, 0, a4Width, a4Width / canvas.width * leftHeight);
                this.dialogVisible = true;
                // this.iframeSrc = pdf.output('dataurlstring');
                // debugger;
                this.pdfSave = pdf.save(pdfFileName + '.pdf')
              } else {
                try {
                  pdf.deletePage(0);
                  // $('.pdfTip').show();
                  // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
                  setTimeout(createImpl, 500, canvas);

                } catch (err) {
                  console.log(err);
                }
              }
            }).then(()=>{
              this.pdfNum += 1
              this.loading = false
            }).then(()=>{
              this.print()
            })

          },
    }
  }
</script>

<style scoped>

</style>
